using System;
using System.Xml;
using System.IO;

namespace UTFramework
{
	public class RegAccess
	{
		private const string XPathTemplate = "//entry[@key='{0}']";
		private const string RegFile = Settings.RegistryFile;
		private static XmlDocument _regDoc;
		
		static RegAccess ()
		{
			_regDoc = new XmlDocument();
			if(File.Exists(RegFile))
			{
				_regDoc.LoadXml(File.ReadAllText(RegFile));
			}
			else
			{
				XmlElement root = _regDoc.CreateElement("reg");
				_regDoc.AppendChild(root);
			}
		}
		
		/// <summary>
		/// Reads the value from Registry.
		/// </summary>
		/// <returns>
		/// The value.
		/// </returns>
		/// <param name='key'>
		/// Key.
		/// </param>
		public static string ReadValue(string key)
		{
			XmlElement element = (XmlElement)_regDoc.SelectSingleNode(string.Format(XPathTemplate,key));
			if(element == null)
				throw new NoEntryException("Your key didn't found in Registry");
			
			return element.Attributes["value"].Value;
		}
		
		/// <summary>
		/// Sets the value into Registry.
		/// </summary>
		/// <param name='key'>
		/// Key.
		/// </param>
		/// <param name='value'>
		/// Value.
		/// </param>
		public static void SetValue(string key, string value)
		{
			XmlElement element = (XmlElement)_regDoc.SelectSingleNode(string.Format(XPathTemplate,key));
			if(element == null)
			{
				CreateElement(key, value);
				_regDoc.Save(RegFile);
				return;
			}
			
			element.Attributes["value"].Value = value;
			
			_regDoc.Save(RegFile);
		}
		
		
		
		private static void CreateElement (string key, string value)
		{
			XmlElement elm = (XmlElement)_regDoc.CreateElement("entry");
			XmlAttribute keyAttr = _regDoc.CreateAttribute("key");
			keyAttr.Value = key;
			elm.Attributes.Append(keyAttr);
			
			XmlAttribute valueAttr = _regDoc.CreateAttribute("value");
			valueAttr.Value = value;
			elm.Attributes.Append(valueAttr);
			
			_regDoc.DocumentElement.AppendChild(elm);
		}
	}
}

